import React from 'react'
import xh1 from '@/assets/8.jpg'
import { useSearchParams } from 'react-router'
import styles from './index.module.less'
import { Revoke, createFromIconfontCN } from '@react-vant/icons'
import { useEffect, useState } from 'react'
import axios from '@/api'
import { formatDate } from '@/utils'
import { useNavigate } from 'react-router'

export default function NoteDetail() {
    const navigate = useNavigate()
    const [searchParams] = useSearchParams()
    const id = searchParams.get('id')
    const IconFont = createFromIconfontCN('//at.alicdn.com/t/c/font_4986959_e1trjaemfnr.js')
    const [note, setNote] = useState({})

    useEffect(() => {
        axios.get(`findNoteById?id=${id}`).then(res => {
            console.log(res)
            setNote(res.data[0])
        }).catch(err => {
            console.log('查询失败', err);
        })
    }, [id])

    const getImageUrl = (item) => {
        try {
            // 如果没有 imges 字段，使用默认图片
            if (!item.images) {
                return xh1;
            }

            // 如果 imges 是字符串，需要解析为JSON
            const images = typeof item.images === 'string' ? JSON.parse(item.images) : item.images;

            // 检查是否是数组格式
            if (Array.isArray(images) && images.length > 0) {
                return images[0].url || xh1;
            }

            // 检查是否是对象格式
            if (images && typeof images === 'object' && images.url) {
                return images.url;
            }

            return xh1; // 如果都不匹配，使用默认图片
        } catch (error) {
            console.log('解析图片数据失败:', error);
            return xh1; // 解析失败时使用默认图片
        }
    }

    return (
        <div className={styles['note-detail']}>
            <div className={styles['note-header']}>
                <span className={styles['back']} onClick={() => { navigate(-1) }}>
                    <Revoke />
                </span>
                <span className={styles['author']}>
                    {note.author}
                </span>
                <span className={styles['share']}>
                    <IconFont name="icon-JC_054" />
                </span>
            </div>
            <div className={styles['note-img']}>
                <img
                    src={getImageUrl(note)}
                    alt={note.title || '笔记图片'}
                // onError={(e) => {
                //     // 图片加载失败时使用默认图片
                //     e.target.src = xh;
                // }}
                />
            </div>
            <div className={styles['note-content']}>
                <div className={styles['title']}>
                    {note.title}
                </div>
                <div className={styles['content']}>
                    {note.content}
                </div>
            </div>
            <div className={styles['time']}>
                {formatDate(note.create_time)}
            </div>
        </div>
    )
}
